import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@utils/SHA256_token_auth.guard";

@Injectable()
export class LongConnsService {
    constructor(
        private authService: AuthGuard
    ) { }

    conns = []
    loginedConns: Map<string, WebSocket> = new Map<string, WebSocket>
    
    addClient(client: WebSocket) {

        //连接后心跳
        const handle = setInterval(() => {
            let userinfo = client["userinfo"]
            if (userinfo) {
                client.send(JSON.stringify({ event: "heatbeat", data: `${userinfo.name}:晚上好!` }))
            } else {
                client.send(JSON.stringify({ event: "heatbeat", data: `心跳` }))
            }
        }, 5000)

        this.conns.push({ client, handle })
    }

    removeClient(client: WebSocket) {
        const index = this.conns.findIndex(c => c.client == client)

        if (index >= 0) {
            let m = this.conns[index]
            clearInterval(m.handle)
            this.conns.splice(index, 1)
        }
    }
    //{"event":"login","data":{"username":"JASON"}}
    async login(client: WebSocket, userId, userInfo) {
        const index = this.conns.findIndex(c => c.client == client)

        if (index >= 0) {
            let user = await this.authService.validateToken(userInfo.token);
            this.loginedConns[user.id] = client
            this.conns.splice(index, 1)
            client["userinfo"] = user

            await this.sendMessage2User(user.id,'login',{message:"登录成功"})
        } else {
            client.close()
        }
    }

    getUserClient(userId): WebSocket {
        let client = this.loginedConns[userId]

        return client
    }

    sendMessage2User(usesrId,event,msg) {
        let client = this.getUserClient(usesrId)

        if (!client) return

        let respMsg = {
            event: event,
            data: msg
        }

        client.send(JSON.stringify(respMsg))
    }

    async pushMessage2User(usesrId, msg) {
       await this.sendMessage2User(usesrId,'pushMessage',msg)
    }
}